
var layer = null;
layui.use(['layer'],function() {
    layer = layui.layer;

    // 清理cookie
    document.cookie = "token=null";
    document.cookie = "current-flink-name=null";

    captcha();
})


function captcha() {
    $.get("/captcha", function (req) {
        $("#captchaImg").attr('src', req.img)
        $("#captchaUid").val(req.uid)
    });
}

function login() {
    const captchaUid = $("#captchaUid").val();
    const captcha = $("#captcha").val();
    const account = $("#account").val();
    const password = $("#password").val();
    if (account.length < 1 || password.length < 1 || captcha.length < 1) {
        layer.msg('请输入账户或密码与验证码！');
        return;
    }

    $.ajax({
        type: "POST",
        url: "/login",
        contentType: "application/json",
        data: JSON.stringify({uid: captchaUid, captcha: captcha, account: account, password: password}),
        success: function (data) {
            const obj = JSON.parse(data);

            if (obj.response_code !== 0){
                layer.msg(obj.response_message);
                return;
            }

            document.cookie = "login-user-name=" + account;
            document.cookie = "token=" + obj.response_token;
            window.location.href = "/";
        }
    });
}